package com.wx.security.service;

import cn.hutool.core.collection.CollUtil;
import com.wx.commons.api.UserApi;
import com.wx.commons.model.UserInfo;
import com.wx.security.constant.MessageConstant;
import com.wx.security.model.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户管理业务类
 * Created by macro on 2020/6/19.
 */
@Service
@Slf4j
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserApi userApi;

    private List<SecurityUser> userList;

    @PostConstruct
    public void initData() {
        userList = new ArrayList<>();
        List<UserInfo> userRoleInfos = userApi.selectUserInfo();
        Map<Long, List<UserInfo>> userRoleMap = userRoleInfos.stream().collect(Collectors.groupingBy(UserInfo::getUserId));
        for (Map.Entry<Long, List<UserInfo>> userRoleEntry : userRoleMap.entrySet()) {
            UserInfo userRoleInfo = userRoleEntry.getValue().get(0);
            int status = userRoleInfo.getRoleStatus() & userRoleInfo.getUserStatus();
            SecurityUser securityUser = SecurityUser.builder()
                    .id(userRoleEntry.getKey())
                    .username(userRoleInfo.getUsername())
                    .password(passwordEncoder.encode(userRoleInfo.getPassword()))
                    .enabled(status == 1)
                    .authorities(userRoleEntry.getValue().stream()
                            .map(UserInfo::getRoleId).distinct().collect(Collectors.toList())
                            .stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()))
                    .tenantId(userRoleInfo.getTenantId())
                    .orgIds(userRoleEntry.getValue().stream().map(UserInfo::getOrgId).distinct().collect(Collectors.toList()))
                    .build();
            userList.add(securityUser);
        }
        log.debug("userList size is {}", userList.size());
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<SecurityUser> findUserList = userList.stream().filter(item -> item.getUsername().equals(username)).collect(Collectors.toList());
        if (CollUtil.isEmpty(findUserList)) {
            throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
        }
        SecurityUser securityUser = findUserList.get(0);
        if (!securityUser.isEnabled()) {
            throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        }
        return securityUser;
    }

}